package com.xiongtian.springframework.core.io;

import cn.hutool.core.lang.Assert;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author: xiongtian
 * @CreateTime: 2025-03-27  10:42
 * @Version: 1.0
 * @Description: 默认资源加载器
 */

public class DefaultResourceLoader implements ResourceLoader {

    /**
     * 根据资源路径获取资源
     * 1. classpath: 前缀的资源
     * 2. http:// 或者 https:// 前缀的资源
     * 3. 其他的资源
     *
     * @param location 资源路径
     * @return
     */
    @Override
    public Resource getResource(String location) {
        Assert.notNull(location, "location must not be null");
        if (location.startsWith(CLASSPATH_URL_PREFIX)) {
            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));
        } else {
            try {
                URL url = new URL(location);
                return new UrlResource(url);
            } catch (MalformedURLException e) {
                return new FileSystemResource(location);
            }
        }
    }
}
